package com.cf.spider.core.controller;

import com.cf.RequiredLogin;
import com.cf.constant.EnumReturnCode;
import com.cf.controller.CommonController;
import com.cf.exception.BizException;
import com.cf.mapper.BeanMapper;
import com.cf.spider.core.controller.vo.JobInfoVo;
import com.cf.spider.core.model.JobInfo;
import com.cf.spider.core.model.service.JobInfoService;
import com.cf.spider.core.model.service.JobTaskService;
import com.cf.vo.ResponseVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;

/**
 * boot-awm-JobInfoController
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/7/11 下午 01:25
 */
@RequestMapping("/jobInfo")
public class JobInfoController extends CommonController<JobInfo, JobInfoService> {
    @Autowired
    private BeanMapper beanMapper;

    @Autowired
    private JobTaskService jobTaskService;

    @Override
    protected String getPageDir() {
        return "jobInfo";
    }

    @Override
    @Deprecated
    @RequestMapping(value = "/deprecated", method = {RequestMethod.POST})
    public ResponseVo<JobInfo> create(JobInfo entity) throws BizException {
        return null;
    }

    @ResponseBody
    @RequiredLogin
    @ApiOperation(value = "创建", notes = "根据post传来的值创建对象")
    @RequestMapping(method = {RequestMethod.POST})
    public ResponseVo<JobInfo> create(@Valid @RequestBody JobInfoVo jobInfoVo, BindingResult bindingResult) throws BizException {
        if (bindingResult.hasFieldErrors()) {
            return ResponseVo.fail(EnumReturnCode.ERROR.getCode(), null, "数据缺失！");
        }
        JobInfo jobInfo = beanMapper.map(jobInfoVo, JobInfo.class);
        String urls = jobInfoVo.getUrls();
        ResponseVo<JobInfo> jobInfoResponseVo = super.create(jobInfo);
        if (jobInfoResponseVo.getData() != null) {
            jobTaskService.addTask(jobInfoResponseVo.getData(), urls);
        }
        return jobInfoResponseVo;
    }
}
